//
//  YSGMyopiaReserveController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2021/1/5.
//  Copyright © 2021 QDSG. All rights reserved.
//

import UIKit

/// 预约检查单
class YSGMyopiaReserveController: BaseViewController {

    @IBOutlet weak var tableView: UITableView!
    
    let inputType: MyopiaReserveInputType
    
    var deviceId: String = "-1"
    
    var viewModel: MyopiaReserveViewModel? {
        didSet {
            tableView.reloadData()
        }
    }
    
    init(inputType: MyopiaReserveInputType) {
        self.inputType = inputType
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "预约检查单"
        initViewModel()
        setUI()
    }
    
    func initViewModel() {
        viewModel = MyopiaReserveViewModel(model: MyopiaReserveModel())
        if inputType == .scan {
            checkHospitalWithDeviceId(deviceId: deviceId)
        }
    }

    // MARK: - UI
    func setUI() {
        tableView.tableFooterView = UIView(frame: CGRect.zero)
        tableView.register(YSGMyopiaReserveCell.nibForCell(),
                           forCellReuseIdentifier: YSGMyopiaReserveCell.reuseIdentifier())
    }
    
    // tableView分组头视图
    func viewForHeader(section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = UIColor.clear
        guard section == 1 else {
            return view
        }
        let label = UILabel()
        label.text = "检查项目"
        label.font = UIFont.medium(15)
        label.textColor = UIColor.mainColor
        view.addSubview(label)
        label.snp.makeConstraints { (make) in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.centerY.equalTo(view.snp.centerY)
        }
        return view
    }
    
    // MARK: - Target
    /// 提交按钮点击
    @IBAction func submitBtnAction(_ sender: UIButton) {
        submitMyopisReserve()
    }
    
    // MARK: - selectedRow
    /// 跳转医院列表
    func pushToHospitalList() {
        let vc = YSGMyopiaHospitalListController()
        vc.selectedClosure = { [weak self] model in
            self?.handleHospitalModel(model: model, deviceId: "", source: "1")
        }
        navigationController?.pushViewController(vc, animated: true)
    }
    
    func handleHospitalModel(model: MyopiaHospitalModel, deviceId: String, source: String) {
        guard var vm = viewModel else { return }
        vm.model.applyHosname = model.hosName
        vm.model.applyHosid = model.hosId
        vm.model.source = source
        vm.model.hosDevId = deviceId
        vm.checkProjectModelAry = model.checkLists
        if source == "0" {
            vm.model.applyCheckTime = Date().toString(format: "yyyy-MM-dd HH:mm")
        }
        viewModel = vm
    }
    
    /// 跳转家庭成员列表，选择就诊人
    func pushToFamily() {
        let familyVc = FamilyViewController()
        familyVc.delegate = self
        navigationController?.pushViewController(familyVc, animated: true)
    }
    
    /// 选择眼别
    func showCheckEyeType() {
        let picker = UINib.loadViewFrom(CommonPickerView.self)
        picker.frame = CGRect(x: 0, y: 0, width: screenW, height: screenH)
        picker.show(type: .checkEyeType)
        picker.selectedClosure = { [weak self] model in
            guard let self = self else { return }
            self.viewModel?.model.checkSeries = model.name
            self.tableView.reloadData()
        }
    }
    
    /// 时间日期选择器
    func showDatePicker() {
        let picker = UINib.loadViewFrom(YSGDatePicker.self)
        picker.dateStr = viewModel?.model.applyCheckTime ?? ""
        picker.delegate = self
        view.addSubview(picker)
    }
    
    /// 选择检查项
    func handleCheckProject(indexPath: IndexPath) {
        guard var vm = viewModel else { return }
        var model = vm.checkProjectModelAry[indexPath.row]
        model.selected = !model.selected
        vm.checkProjectModelAry[indexPath.row] = model
        viewModel = vm
    }
    
    //MARK: - Navigator
    /// 跳转预约结果
    func pushToReserveResult() {
        guard let vm = viewModel else { return }
        let vc = YSGMyopiaReserveResultController(viewModel: vm)
        navigationController?.pushViewController(vc, animated: true)
    }
    
}

extension YSGMyopiaReserveController: UITableViewDataSource, UITableViewDelegate {
    
    // MARK: - UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel?.numberOfRows(section: section) ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: YSGMyopiaReserveCell.reuseIdentifier(), for: indexPath) as! YSGMyopiaReserveCell
        if let vm = viewModel {
            cell.updateCellWithVm(vm: vm, indexPath: indexPath)
        }
        
        return cell
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel?.numberOfSection ?? 0
    }
    
    
    // MARK: - UITableViewDelegate
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 45
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return viewModel?.heightForHeader(section: section) ?? 0
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return viewForHeader(section: section)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            if indexPath.row == 0 {
                pushToHospitalList()
            }
            if indexPath.row == 1 {
                showCheckEyeType()
            }
            if indexPath.row == 2 {
                pushToFamily()
            }
        }
        
        if indexPath.section == 1 {
            handleCheckProject(indexPath: indexPath)
        }
        
        if indexPath.section == 2 {
            showDatePicker()
        }
    }
}

extension YSGMyopiaReserveController: FamilyViewControllerDelegate, YSGDatePickerDelege{
    // MARK: - FamilyViewControllerDelegate 选择就诊人代理
    func familyVc(_ vc: FamilyViewController, didSelected vm: FamilyRowViewModel) {
        viewModel?.model.applyPatid = vm.patientId
        viewModel?.model.applyPatname = vm.name
    }
    
    // MARK: - YSGDatePickerDelege 选择检查时间代理
    func YSGDatePickerConfirmBtnAction(dateStr: String) {
        viewModel?.model.applyCheckTime = dateStr
    }
}

// MARK: - 请求数据
extension YSGMyopiaReserveController {
    func submitMyopisReserve() {
        guard let vm = viewModel else { return }
        guard vm.submitAvailable().isEmpty else {
            HUDTool.show(message: vm.submitAvailable())
            return
        }
        HUDTool.showActivity()
        MyopiaReserveViewModel.submitMyopisReserve(vm: vm) { (error, code) in
            HUDTool.hideActivity()
            switch code {
            case .failure:
                HUDTool.show(message: error)
            case .success:
                self.pushToReserveResult()
            }
        }
    }
    
    func checkHospitalWithDeviceId(deviceId: String) {
        HUDTool.showActivity()
        MyopiaHospitalViewModel.getMyopiaHospitalList(hosDeviceId: deviceId, hosName: "") { (models, error, code) in
            HUDTool.hideActivity()
            switch code {
            case .failure:
                HUDTool.show(message: error)
            case .success:
                guard models.count > 0 else {
                    HUDTool.show(message: "未查询到信息，请手动填写")
                    return
                }
                let model = models[0]
                self.handleHospitalModel(model: model, deviceId: deviceId, source: "0")
            }
        }
    }
}
